package com.shengtsource.boot.initializer;


import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.annotation.HandlesTypes;
import java.lang.reflect.Modifier;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * 自定义Servlet容器初始化器,这里会扫描实现WebApplicationInitializer接口的实现类，并且
 * 在去重后循环调用初始化器的onStartup方法
 * @author shengsource
 */
@HandlesTypes(WebApplicationInitializer.class)
public class MySpringServletContainerInitializer implements ServletContainerInitializer {
    @Override
    public void onStartup(Set<Class<?>> set, ServletContext servletContext) {

        Set<WebApplicationInitializer> initializerSet = new LinkedHashSet<WebApplicationInitializer>(set.size());
        for (Class<?> initializerClazz : set) {
            Object instance = null;
            try {
                //实例化WebApplicationInitializer对象
                instance = initializerClazz.newInstance();
                //如果是WebApplicationInitializer类型，并且不是接口、不是抽象类，放置在set集合中
                if(!initializerClazz.isInterface() && !Modifier.isAbstract(initializerClazz.getModifiers()) && instance instanceof WebApplicationInitializer) {
                    initializerSet.add((WebApplicationInitializer) instance);
                }

            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        //循环遍历，调用初始化器onStartup方法
        initializerSet.stream().forEach(initializer -> {
            initializer.onStartup(servletContext);
        });
    }
}
